package com.professionalandroid.apps.compass;

import android.app.Application;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import java.util.Timer;
import java.util.TimerTask;

//import static android.support.v4.content.ContextCompat.getSystemService;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BlankFragment3#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment3 extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public BlankFragment3() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment3.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment3 newInstance(String param1, String param2) {
        BlankFragment3 fragment = new BlankFragment3();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }








    private CompassView2 mCompassView;
    private SensorManager mSensorManager;
    private int mScreenRotation;
    private float[] mNewestValues;

    private void updateOrientation(float[] values) {
        if (mCompassView!= null) {
            mCompassView.setBearing(values[0]);
            mCompassView.setPitch(values[1]);
            mCompassView.setRoll(-values[2]);
            mCompassView.invalidate();
        }
    }

    private float[] calculateOrientation(float[] values) {
        float[] rotationMatrix = new float[9];
        float[] remappedMatrix = new float[9];
        float[] orientation = new float[3];

        // Determine the rotation matrix
        SensorManager.getRotationMatrixFromVector(rotationMatrix, values);

        // Remap the coordinates based on the natural device orientation.
        int x_axis = SensorManager.AXIS_X;
        int y_axis = SensorManager.AXIS_Y;
        switch (mScreenRotation) {
            case (Surface.ROTATION_90):
                x_axis = SensorManager.AXIS_Y;
                y_axis = SensorManager.AXIS_MINUS_X;
                break;
            case (Surface.ROTATION_180):
                y_axis = SensorManager.AXIS_MINUS_Y;
                break;
            case (Surface.ROTATION_270):
                x_axis = SensorManager.AXIS_MINUS_Y;
                y_axis = SensorManager.AXIS_X;
                break;
            default: break;
        }

        SensorManager.remapCoordinateSystem(rotationMatrix,
                x_axis, y_axis,
                remappedMatrix);

        // Obtain the current, corrected orientation.
        SensorManager.getOrientation(remappedMatrix, orientation);

        // Convert from Radians to Degrees.
        values[0] = (float) Math.toDegrees(orientation[0]);
        values[1] = (float) Math.toDegrees(orientation[1]);
        values[2] = (float) Math.toDegrees(orientation[2]);
        return values;
    }

    private final SensorEventListener mSensorEventListener
            = new SensorEventListener() {
        public void onSensorChanged(SensorEvent sensorEvent) {
            mNewestValues = calculateOrientation(sensorEvent.values);
        }
        public void onAccuracyChanged(Sensor sensor, int accuracy) {}
    };

    private void updateGUI() {
//        runOnUiThread(new Runnable() {
//            public void run() {
//                updateOrientation(mNewestValues);
//            }
//        });
        updateOrientation(mNewestValues);
    }









    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }




    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment



        View view = inflater.inflate(R.layout.fragment_compassview3, container, false);

        mCompassView = view.findViewById(R.id.compassView3);


        mSensorManager = (SensorManager) view.getContext().getSystemService(android.content.Context.SENSOR_SERVICE);
        WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);

        Display display = wm.getDefaultDisplay();
        mScreenRotation = display.getRotation();

        mNewestValues = new float[] {0, 0, 0};

        Timer updateTimer = new Timer("compassUpdate");
        updateTimer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                updateGUI();
            }
        }, 0, 100);//1000/60


        return view;

    }


    @Override
    public void onResume() {
        super.onResume();
        Sensor rotationVector = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
        mSensorManager.registerListener(mSensorEventListener,
                rotationVector,
                SensorManager.SENSOR_DELAY_FASTEST);
    }

    @Override
    public void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(mSensorEventListener);
    }
}